package linwen.wang.controller;

import linwen.wang.commom.ReturnVO;
import linwen.wang.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Date;
import java.util.Set;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author zero
 * @DATE 2023/8/2 8:16 AM
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    /***
     springboot中默认注入了这个校验类
     如果是spring中使用可以做如下配置
     @Bean
     public Validator validator() {
         return new LocalValidatorFactoryBean();
         }
     **/

    @Autowired
    private Validator validator;


    @PostMapping
    public Object saveList(@RequestBody User user) {
        Integer id = user.getId();
        User user1 = new User();
        user1.setId(id+10000);
        user1.setAge(18);
        user1.setUsername("zhangsan");
        user1.setPhone("17645369846");
        user1.setEmail("3455@qq.com");
        user1.setPassword("4343");
        user1.setBirthday(new Date());
        // 校验对象并生成错误信息
        Set<ConstraintViolation<User>> validated = validator.validate(user1);
        if(!CollectionUtils.isEmpty(validated)){
            StringBuilder stringBuilder = new StringBuilder("校验不通过：");
            validated.forEach(item->{
                stringBuilder.append(item.getMessage());
            });
            return ReturnVO.buildErrorReturnVO("param error",stringBuilder);
        }
        // 校验通过，才会执行业务逻辑处理
        return ReturnVO.buildReturnVO("success");
    }

    // 还可以使用Hibernate Validation 提供的 Validator，写成util或者注册成一个bean进行校验。
    public static void main(String[] args) {
        User user1 = new User();
        user1.setId(100005);
        user1.setAge(18);
        user1.setUsername("zhangsan");
        user1.setPhone("17645369846");
        user1.setEmail("3455@qq.com");
        user1.setPassword("4343");
        user1.setBirthday(new Date());
        // 校验对象并生成错误信息
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        Validator validator = vf.getValidator();
        Set<ConstraintViolation<User>> validated = validator.validate(user1);
        if(!CollectionUtils.isEmpty(validated)){
            StringBuilder stringBuilder = new StringBuilder("校验不通过：");
            validated.forEach(item->{
                stringBuilder.append(item.getMessage());
            });
            System.out.println(stringBuilder);
        }
        System.out.println("valided success");
    }
}
